<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <!-- 使用双向绑定的方式获取查询的参数 -->
          <el-input v-model="filters.keywords" placeholder="输入名称或地址或电话"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="shopQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" disabled @click="handleAdd">新增</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>


        <el-form-item>
             <!-- 默认name="file" i
                list-type: 上传文件的类型
             -->
             <el-upload class="upload-demo"
                 action="http://localhost:8080/shop/importExcel"
                 list-type="text">
              <el-button type="warning">导入</el-button>
           </el-upload>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
  <!--
     data: 表单中的数据绑定
     v-loading: 忙等框
     selection-change: 用于表中复选框选择的触发的事件，做批量操作
     Shops：页面加载完后发送请求由后台查询出数据响应到前台 []

      id
      name
      tel
      registerTime
      state
      address
      logo
      admin_id

    -->
    <el-table :data="Shops" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>

      <el-table-column prop="name" label="名称" width="120" sortable>
      </el-table-column>

      <el-table-column prop="admin.username" label="店长" width="120" sortable>
      </el-table-column>

      <el-table-column prop="tel" label="电话" width="120" sortable>
      </el-table-column>

      <el-table-column prop="registerTime" label="注册时间" width="120" sortable>
      </el-table-column>

      <el-table-column prop="address" label="地址" width="250" sortable>
      </el-table-column>

<!--      <el-table-column label="标志" width="150" sortable>
        <template slot-scope="scope">
          <el-image :src="PREFIXOFPATH+scope.row.logo" alt style="width: 100px;">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>

      </el-table-column>-->
      <el-table-column prop="logo" label="图标" width="150" sortable>
        <template scope="scope">
          <img :src="imgPrefix+scope.row.logo" width="50px">
        </template>
      </el-table-column>




      <!--<el-table-column prop="state" label="是否启用" width="100" :formatter="formatSex" sortable>
      </el-table-column>-->
      <el-table-column label="状态" width="100">
        <template scope="scope">
          <span style="color: #8e8e8e" v-if="scope.row.state == 1">待审核</span>
          <span style="color: #d000ff" v-else-if="scope.row.state == 2">待激活</span>
          <span style="color: #11ff00" v-else-if="scope.row.state == 3">正常使用</span>
          <span style="color: #ff0000" v-else-if="scope.row.state == 4">驳回</span>
        </template>
      </el-table-column>



      <el-table-column label="操作" width="300">
        <template scope="scope">
          <el-button size="small" disabled @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" disabled size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" :disabled="scope.row.state!==1" size="small" @click="handleAudit(scope.$index, scope.row)">店铺审核</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--   disabled: 使按钮失效   -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
           @current-change="handleCurrentChange"
           :page-size="pageSize"
           :total="totals"
           style="float:right;">

      </el-pagination>
    </el-col>

    <!-- 审核模态框 -->
    <el-dialog title="审核店铺" :visible.sync="shopAuditVisible" :close-on-click-modal="false">
      <el-form :model="shopAuditLog" label-width="80px"  ref="shopAuditLogForm">
        <el-form-item label="备注" prop="note">
          <el-input type="textarea" v-model="shopAuditLog.note"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="shopAuditVisible = false">取消</el-button>
        <el-button type="primary" @click.native="auditPass">通过</el-button>
        <el-button type="primary" @click.native="auditReject">驳回</el-button>
      </div>
    </el-dialog>



    <!--编辑界面
      rules: 表单验证，用于判断用户是否输入数据
      ref： 点击提交按钮时，再次验证是否输入数据 - 为当前模态框取名

      id
      name
      tel
      registerTime
      state
      address
      logo
      admin_id
    -->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">

      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">

        <el-form-item label="店铺名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="tel">
          <el-input v-model="editForm.tel" auto-complete="off"></el-input>
        </el-form-item>


        <!--

          店长：是shop_id为 当前shop的id 的 员工中的一个
         -->
        <el-form-item label="店长" prop="admin_id">
          <!--

          el-select  下拉框
		      v-model="editForm.manager_id" - 回显数据
		      value-key	作为 value 唯一标识的键名，绑定值为对象类型时必填
		      回显机制：

		      v-model="editForm.manager_id" 与 :value="item.id"对应(v-for中的变量的item中的id)对应
		      如果item中的id与manager_id相同则显示label绑定的item.username
		      注意：v-model=""中的值要与 :value=""中的值类型对应

		      具体例子可以参见官网
          //验证回显的数据绑定
          -->
          <el-select v-model="editForm.admin_id" placeholder="请选择" clearable>

            <!--
                v-for: 循环
                key：一个键值，唯一即可

                label：选择后或初始时匹配到的要显示的数据
                value：向后台发送的数据
            -->
            <el-option
                v-for="item in shop_emps"
                :key="item.id"
                :label="item.username"
                :value="item.id">

              <!--下拉单中显示的内容-->
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="标志" prop="logo" >
          <el-input v-model="editForm.logo" auto-complete="off"></el-input>
        </el-form-item>


        <el-form-item label="注册时间" prop="registerTime">
          <!--<el-input v-model="editForm.registerTime" auto-complete="off"></el-input>-->
          <el-date-picker
              v-model="editForm.registerTime"
              type="date"
              placeholder="选择日期"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd">
          </el-date-picker>

        </el-form-item>



        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">待审核</el-radio>
            <el-radio class="radio" :label="2">待激活</el-radio>
            <el-radio class="radio" :label="3">正常使用</el-radio>
            <el-radio class="radio" :label="4">驳回</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>

export default {
  data() {
    return {

      //审核模态框
      shopAuditVisible: false,
      //编辑界面数据
      shopAuditLog: {
        shop_id: null,
        note:'',
        //操作人员的id
        audit_id: null,
      },

      //PREFIXOFPATH: "http://123.207.27.208",
      imgPrefix: "http://123.207.27.208",
      shop_emps: [],
      title: "",
      filters: {
        keywords: ''
      },
      Shops: [],
      totals: 0,
      currentPage: 1,
      pageSize: 5,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        /**
         * id: null,
         name: "",
         tel: "",
         registerTime: null,
         state: 1,
         address: "",
         logo: null,
         admin_id: null,
         */

        name: [
          { required: true, message: '请输入店铺名称', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入电话', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        /*registerTime: [
          { required: true, message: '请输入注册时间 ', trigger: 'change' }
        ],
        logo: [
          { required: true, message: '请输入标志', trigger: 'change' }
        ],
        state: [
          { required: true, message: '请输入状态', trigger: 'change' }
        ],
        admin_id: [
          { required: true, message: '请输入店长', trigger: 'change' }
        ],*/
      },
      //编辑界面数据
      editForm: {
        id: null,
        name: "",
        tel: "",
        registerTime: null,
        state: 1,
        address: "",
        logo: null,
        admin_id: null,
      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      /*addForm: {
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: ''
      }*/

    }
  },
  methods: {
    handleExport(){
      //发送请求导出excel文件
      //即修改url值可发送请求
      location.href = "http://localhost:8080/shop/exportExcel";

    },

    //审核通过点击按钮的绑定函数
    auditPass(){
      this.$http.post("/shop/audit/pass", this.shopAuditLog)
        .then(res => {
        if(res.data.success){

          this.$message({
            message: '审核成功',
            type: 'success'
          });
        }else{
          //删除失败
          this.$message({
            message: res.data.message,
            type: 'error'
          });
        }

        //关闭模态框
        this.shopAuditVisible = false;

        //刷新页面
        this.getShops();

      }).catch(res => {
        //发生异常或错误时执行
        this.$message({
          message: '系统异常，稍后重试',
          type: 'error'
        });

        //关闭模态框
        this.shopAuditVisible = false;

        //刷新页面
        this.getShops();
      });
    },

    //审核驳回的点击按钮绑定的函数
    auditReject(){

      this.$http.post("/shop/audit/reject", this.shopAuditLog)
          .then(res => {
            if(res.data.success){

              this.$message({
                message: '驳回成功',
                type: 'success'
              });
            }else{
              //删除失败
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }

            //关闭模态框
            this.shopAuditVisible = false;

            //刷新页面
            this.getShops();

          }).catch(res => {
        //发生异常或错误时执行
        this.$message({
          message: '系统异常，稍后重试',
          type: 'error'
        });

        //关闭模态框
        this.shopAuditVisible = false;

        //刷新页面
        this.getShops();
      });

    },


    //点击店铺审核弹出模态框
    handleAudit(index, row){
      //清除之前的note数据
      this.shopAuditLog.note = '';
      this.shopAuditLog.shop_id = row.id;
      this.shopAuditVisible = true;
    },


    //性别显示转换
    /*formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },*/
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getShops();
    },
    

    //获取编辑模态框中店铺店长的回显数据
    getShopEmps() {
       this.$http.get("/employee").then(res=>this.shop_emps = res.data);
    },



    /**
     * 问题：当在非第一页查询时，如果条件查询的结果没有超过一页数据，则会显示空屏，
     * 解决：条件查询配合分页查询，显示第一页的数据
     */
    shopQuery(){
      this.currentPage  = 1;
      this.getShops();
    },

    //获取用户列表
    getShops() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.filters.keywords
      };
      this.listLoading = true;


      //发送异步请求获取数据
      this.$http.put("/shop", para)
          .then(res => {
            //alert("success")
            //关闭忙等框
            this.listLoading = false;
            this.totals = res.data.totals;
            this.Shops = res.data.data;
          }).catch(res => alert("fail!"));
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        //提示框
        type: 'warning'
      }).then(() => {
        //当点击确认时执行

        //忙等框
        this.listLoading = true;

        //获取数据发送请求
        this.$http.delete("/shop/" + row.id)
            .then(res => {
                //关闭忙等框
                if(res.data.success){
                  //成功删除
                  this.$message({
                    message: '删除成功',
                    type: 'success'
                  });
                }else{
                  //删除失败
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

              //操作完成后，刷新页面
              //当删除完当前页面的最后一条数据后，可以就显示空页面
              //或者每次删除完就重新显示第一页数据
              // this.currentPage = 1;
              this.getShops();

            }).catch(res => {
              //发生异常或错误时执行
              this.$message({
                message: '系统异常，稍后重试',
                type: 'error'
          });

        });

        //NProgress.start();
        /*let para = { id: row.id };
        removeShop(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getShops();
        });*/
      }).catch(() => {
        //点击取消时执行
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";

      //获取模态框中店长回显的数据
      this.getShopEmps();

      this.editFormVisible = true;

      //通过克隆方式获取回显数据
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      //修改标题
      this.title = "增加";

      //获取模态框中店长回显的数据
      this.getShopEmps();

      //清空模态框
      this.editForm = {
        id: null,
        name: "",
        tel: "",
        registerTime: null,
        state: 1,
        address: "",
        logo: null,
        admin_id: null,
      },

      this.editFormVisible = true;

    },
    //编辑页面的提交按钮的事件绑定函数
    editSubmit: function () {

      //this.$refs.editForm 表单的验证
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();

            //通过克隆，获取一份数据，因为使用的是双向绑定
            let para = Object.assign({}, this.editForm);

            //发送请求
            this.$http.post("/shop", para)
              .then(res => {
                //关闭忙等框
                this.editLoading = false;


                if(res.data.success) {
                  //操作成功

                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  });


                }else {
                  //操作失败

                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                }

                //关闭模态框
                this.editFormVisible = false;

                //刷新页面
                this.getShops();

              }).catch(res => {
                //发生异常

                //关闭忙等框
                this.editLoading = false;
                this.$message({
                  message: '网络延时，请稍后重试',
                  type: 'error'
                });


                //关闭模态框
                this.editFormVisible = false;

                //刷新页面
                this.getShops();
            })

          });
        }
      });
    },


    selsChange: function (sels) {
      //复选框选择时将选择的数据记录到data数据模型中的sels中
      this.sels = sels;
      console.log(sels);
    },


    //批量删除
    batchRemove: function () {

      //map 数组的方法映射
      var ids = this.sels.map(item => item.id);


      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        /*let para = { ids: ids };
        batchRemoveShop(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getShops();
        });*/

        //发送请求
        this.$http.patch("/shop", ids).then((res) => {
          this.listLoading = false;

          if(res.data.success) {
            //success
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }

          //操作成功后刷新页面，可以继续查询当前页的内容,即使当前页的数据被删除完
          this.getShops();

        }).catch(res =>{
          //当产生异常时
          this.listLoading = false;
          this.$message({
            message: '网络延迟，请稍后重试！',
            type: 'error'
          });
        });
      }).catch(() => {
        //点击取消按钮
      });
    }
  },
  mounted() {
    this.getShops();

    let logininfo = localStorage.getItem("logininfo");
    if (logininfo) {
      // 将Json格式的字符串形式转化为对象
      logininfo = JSON.parse(logininfo);

      //初始化操作人员的id（audit_id）
      this.shopAuditLog.audit_id = logininfo.id;
    }

  }
}

</script>

<style scoped>

</style>
